package cn.bj.yu.unsafe;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author 周宇
 * @create 2020-08-12 15:45
 * 异常：ConcurrentModificationException
 */
public class UnSafeMap {
    public static void main(String[] args) {
        //map 是这样用的么？ 默认等价于什么？
        //Map<String, Object> map = new HashMap<>();
        // 等价于 初始容量1<<4=16 加载因子0.75f
        //Map<String, Object> map = new HashMap(1 << 4, 0.75f);
        Map<String, Object> map = new ConcurrentHashMap<>();

        /**
         * 解决方案：
         * 1、Map<String, Object> map = Collections.synchronizedMap(new HashMap<>());
         * 2、Map<String, Object> map = new ConcurrentHashMap<>();
         * 研究ConcurrentHashMap原理
         */
        for (int i = 1; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}